from pycocotools.coco import COCO
import cv2
 
def showImages(image_path, annFile):
    """
    :param image_path: 标注图片的地址
    :param annFile:使用的标注文件
    """
    coco = COCO(annFile)
    image = cv2.imread(image_path)
    imageName = image_path.split('/')[-1]
    imagesInfo = coco.dataset['images']
    for img in imagesInfo:
        if img['file_name'] == imageName:
            pic_id = img['id']
            print(pic_id)
    annIds = coco.getAnnIds(imgIds=pic_id, iscrowd=None)
    anns = coco.loadAnns(annIds)
    #print(anns)
    x, y, w, h = anns[0]['bbox']
    catIds = anns[0]['category_id']
    x, y, w, h = int(x), int(y), int(w), int(h)
    # print(x, y, w, h)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255))
    cv2.putText(image, str(catIds), (x-2,y-5), cv2.FONT_HERSHEY_SIMPLEX , 0.75, (0, 0, 255), 1)
    cv2.imshow('coco', image)
    cv2.waitKey(0)

if __name__ == '__main__':
    showImages('train_dataset/JPEGImages/00001-arithmetic.jpg', 'train_dataset/annotations.json')